package com.xiaozhengkeji.mchttpapi.tcp;

import com.xiaozhengkeji.mchttpapi.tools.Mes;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.command.defaults.BukkitCommand;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {
    private ServerSocket server;

    public TcpServer(Integer ServerPort) {
        try {
            server = new ServerSocket(ServerPort);
        } catch (IOException e) {

        }
    }

    //启动监控
    public void talk() {
        while (true) {
            try {
                Socket sc = server.accept();
                DataInputStream din = new DataInputStream(sc.getInputStream());
                DataOutputStream dout = new DataOutputStream(sc.getOutputStream());
                String smg = din.readUTF();
                Mes.logServer("接收到: " + smg);
                boolean re = Bukkit.dispatchCommand(Bukkit.getConsoleSender(), smg);
                Mes.logServer("执行完成: " + re);
                dout.writeUTF(String.valueOf(re));
                //关闭本次资源
                din.close();
                dout.close();
                sc.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
